package com.sunday.player.service;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;

public class sundayplayerProvider extends ContentProvider {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    
    
    private SQLiteDatabase internalDB =null;
    public static final String AUTHORITY = "com.sunday.player.service.sundayplayerProvider";
    public static final String INTERNAL_DB_NAME = "sundayPlayer.db";
    private static final int DB_VERSION = 2;
    private static final UriMatcher MATCHER;
    public static SQLiteDatabase gDB;
    private static final int LISTINFO = 1;
    private static final int LISTINFO_ID=2;
    	
    private static final int MUSICINFO = 3;
    private static final int MUSICINFO_ID=4;
        
    private static final int PLAYLIST = 5;
    private static final int PLAYLIST_ID= 6;
    
    
    
    private static final String Tablename_music = "musicinfo";
    private static final String Tablename_playList = "playList";
    
    
    public static final class listInfo implements BaseColumns{
	public static final Uri CONTENT_URI_LIST = Uri.parse("content://"+AUTHORITY+"/listinfo");
    }
    public static final class musicInfo implements BaseColumns{
	public static final Uri CONTENT_URI_MUSIC = Uri.parse("content://"+AUTHORITY+"/"+Tablename_music);
    }
    public static final class playlist implements BaseColumns{
	public static final Uri CONTENT_URI_PLayList = Uri.parse("content://"+AUTHORITY+"/"+Tablename_playList);
    }
        
    static {
	MATCHER=new UriMatcher(UriMatcher.NO_MATCH);
	MATCHER.addURI(AUTHORITY, "listinfo", LISTINFO);
	MATCHER.addURI(AUTHORITY, "listinfo/#", LISTINFO_ID);
	
	MATCHER.addURI(AUTHORITY, Tablename_music, MUSICINFO);
	MATCHER.addURI(AUTHORITY, Tablename_music+"/#", MUSICINFO_ID);
	
	MATCHER.addURI(AUTHORITY, Tablename_playList, PLAYLIST);
	MATCHER.addURI(AUTHORITY, Tablename_playList+"/#", PLAYLIST_ID);
	
	
    }
    
    public final static String[] MusicList  = new String[]{
	"_id",
	"listname",
	"isplayeanble",
	"count"
    };
    
    public final static String[] MusicInfo = new String[]{
	"_id",
	"listid",
	"title",
	"track",
	"duration",
	"album_id",
	"album",
	"artist_id",
	"artist",
	"_data",
	"playcount",
	"url"
    };
    
    
    
    private class InternalDatabase extends SQLiteOpenHelper {

	public InternalDatabase(Context context, String name,CursorFactory factory, int version) {
	    super(context, name, factory, version);

	}
	public InternalDatabase(Context context) {
	    super(context, INTERNAL_DB_NAME, null, DB_VERSION);
	}
	

	@Override
	public void onCreate(SQLiteDatabase db) {
	    db.beginTransaction();
	    try {
		String list = 
			"CREATE TABLE  listinfo ("+
			"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
			"listname TEXT,"+
			"isplayeanble INTEGER DEFAULT '0'," +
			"count INTEGER "+
			
		");";
		db.execSQL(list);
		
		String MusicInfo = 
			"CREATE TABLE IF NOT EXISTS "+Tablename_music+" ("+
			"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
			sundayplayerProvider.MusicInfo[1] +" TEXT ," +
			sundayplayerProvider.MusicInfo[2] +" TEXT ," +
			sundayplayerProvider.MusicInfo[3] +" INTEGER,"+
			sundayplayerProvider.MusicInfo[4] +" TEXT,"+
			sundayplayerProvider.MusicInfo[5] +" TEXT,"+
			sundayplayerProvider.MusicInfo[6] +" TEXT,"+
			sundayplayerProvider.MusicInfo[7] +" TEXT,"+
			sundayplayerProvider.MusicInfo[8] +" TEXT,"+
			sundayplayerProvider.MusicInfo[9] +" TEXT,"+
			sundayplayerProvider.MusicInfo[10] +" INTEGER,"+
			"url TEXT"+
			
			
		");";
		db.execSQL(MusicInfo);
		
		String PLayList = 
			"CREATE TABLE IF NOT EXISTS "+Tablename_playList+" ("+
			sundayplayerProvider.MusicInfo[0] +" INTEGER ,"+
			sundayplayerProvider.MusicInfo[1] +" TEXT ," +
			sundayplayerProvider.MusicInfo[2] +" TEXT ," +
			sundayplayerProvider.MusicInfo[3] +" INTEGER,"+
			sundayplayerProvider.MusicInfo[4] +" TEXT,"+
			sundayplayerProvider.MusicInfo[5] +" TEXT,"+
			sundayplayerProvider.MusicInfo[6] +" TEXT,"+
			sundayplayerProvider.MusicInfo[7] +" TEXT,"+
			sundayplayerProvider.MusicInfo[8] +" TEXT,"+
			sundayplayerProvider.MusicInfo[9] +" TEXT,"+
			sundayplayerProvider.MusicInfo[10] +" INTEGER,"+
			"url TEXT"+
			
			
		");";
		db.execSQL(PLayList);
		db.setTransactionSuccessful();
            } catch (Exception e) {
            	e.printStackTrace();
            	return;
            } finally {
            	db.endTransaction();
            }
	    db.setVersion(DB_VERSION);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	    if(db.getVersion() < newVersion){
		
		
		
		db.setVersion(DB_VERSION);
	    }
		
	}
	
    }
    
    
    
    



    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
	int count;
	int colectionType = getCollectionType(uri);
	count = internalDB.delete(getTableName(colectionType), selection, selectionArgs);
	getContext().getContentResolver().notifyChange(uri, null);
	return count;
    }
    private int getCollectionType(Uri url) {
	int ret = MATCHER.match(url);
	return ret;
    }
    private String getTableName(int colectionType) {
	String ret = "";
	switch(colectionType) {
		case LISTINFO:
		case LISTINFO_ID:
			ret = "listinfo";
			break;
			
		case MUSICINFO:
		case MUSICINFO_ID:
			ret = Tablename_music;
			break;
		case PLAYLIST:
		case PLAYLIST_ID:
			ret = Tablename_playList;
			break;
			
			
			
	}
	return ret;
    }

    @Override
    public String getType(Uri uri) {
	switch (getCollectionType(uri)) {
	case LISTINFO:
		return "vnd.android.cursor.dir/vnd.sunday."+getTableName(LISTINFO);
	case LISTINFO_ID:
		return "vnd.android.cursor.item/vnd.sunday."+getTableName(LISTINFO_ID);
	case MUSICINFO:
		return "vnd.android.cursor.dir/vnd.sunday."+getTableName(MUSICINFO);
	case MUSICINFO_ID:
		return "vnd.android.cursor.item/vnd.sunday."+getTableName(MUSICINFO_ID);
	case PLAYLIST:
		return "vnd.android.cursor.dir/vnd.sunday."+getTableName(PLAYLIST);
	case PLAYLIST_ID:
		return "vnd.android.cursor.item/vnd.sunday."+getTableName(PLAYLIST_ID);
	
	
	
	}
	
        return "";
    }



    @Override
    public Uri insert(Uri uri, ContentValues values) {
	try {
	    long rowID;
		int collectionType = getCollectionType(uri);
		switch (collectionType) {

		default:
			rowID= internalDB.insert(getTableName(collectionType), "", values);
			break;
		}
		
		if (rowID > 0) {
			Uri _uri = ContentUris.withAppendedId(getUri(collectionType), rowID);
			getContext().getContentResolver().notifyChange(_uri, null);
			return _uri;
		}
	} catch (Exception e) {

	    e.printStackTrace();

	}
	throw new SQLException("Failed to insert row into " + uri);

	
    }


	private Uri getUri(int collectionType) {
		switch (collectionType)
		{
			case LISTINFO:
			case LISTINFO_ID:
			    return  sundayplayerProvider.listInfo.CONTENT_URI_LIST;
				
			case MUSICINFO:
			case MUSICINFO_ID:
			    return  sundayplayerProvider.musicInfo.CONTENT_URI_MUSIC;
			case PLAYLIST:
			case PLAYLIST_ID:
			    return  sundayplayerProvider.playlist.CONTENT_URI_PLayList;
			default:
			    
			    break;
					
		}
		return null;
	}

    @Override
    public boolean onCreate() {
	internalDB = (new InternalDatabase(getContext(), INTERNAL_DB_NAME, null, DB_VERSION)).getWritableDatabase();
	if(internalDB != null) {
		gDB = internalDB;
			
		return true;
	}
	return false;
    }



    @Override
    public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {
	
	Cursor c= null;
	try {
	    SQLiteQueryBuilder qb=new SQLiteQueryBuilder();
		int collectionType = getCollectionType(uri);
		qb.setTables(getTableName(collectionType));
		qb.setProjectionMap(getDefaultProjection(collectionType));
	         c=qb.query(internalDB, projection, selection, selectionArgs,	null, null, sortOrder);
	        c.setNotificationUri(getContext().getContentResolver(), uri);
	} catch (Exception e) {
	    e.printStackTrace();
	}
	
        return c;
	
    }


    private HashMap<String, String> getDefaultProjection(int collectiontype) {
	return null;
    }
    @Override
    public int update(Uri uri, ContentValues values, String selection,
	    String[] selectionArgs) {
	int count = 0;
	int colectionType = getCollectionType(uri);
	count = internalDB.update(getTableName(colectionType), values, selection, selectionArgs);
	getContext().getContentResolver().notifyChange(uri, null);
	return count;
    }

}
